package cn.jeeweb.modules.flood.service.impl;

import cn.jeeweb.core.common.service.impl.CommonServiceImpl;
import cn.jeeweb.core.query.data.QueryRequest;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.modules.constant.FloodStockChangeTypeEnum;
import cn.jeeweb.modules.constant.FloodStockRecordStatusEnum;
import cn.jeeweb.modules.flood.entity.FloodAssetsStock;
import cn.jeeweb.modules.flood.mapper.FloodAssetsStockRecordMapper;
import cn.jeeweb.modules.flood.entity.FloodAssetsStockRecord;
import cn.jeeweb.modules.flood.service.IFloodAssetsStockRecordService;
import cn.jeeweb.modules.flood.service.IFloodAssetsStockService;
import cn.jeeweb.modules.sys.entity.User;
import cn.jeeweb.modules.sys.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.ff.common.service.FFException;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author liyonglei
 * @version V1.0
 * @Title: 库存统计查询
 * @Description: 库存统计查询
 * @date 2018-11-23 15:27:46
 */
@Transactional
@Service("floodAssetsStockRecordService")
public class FloodAssetsStockRecordServiceImpl extends CommonServiceImpl<FloodAssetsStockRecordMapper, FloodAssetsStockRecord> implements IFloodAssetsStockRecordService {

    protected Logger log = Logger.getLogger(getClass());
    @Autowired
    private IFloodAssetsStockService assetsStockService;

    @Override
    public boolean insert(FloodAssetsStockRecord entity) {
        User user = UserUtils.getUser();
        entity.setChangeType(FloodStockChangeTypeEnum.IN.getName());
        entity.setStatus(FloodStockRecordStatusEnum.TO_CHECK.getValue());          //待审核
        entity.setApplyUserId(user.getId());
        entity.setApplyUserName(user.getUsername());
        entity.setApplyUserRealName(user.getRealname());
        return super.insert(entity);
    }

    @Override
    public boolean insertOrUpdate(FloodAssetsStockRecord entity) {
        User user = UserUtils.getUser();
        log.info("FloodAssetsStockRecordService>>>>>>>>>>>insertOrUpdate>>>>>>>>> record is :" + JSON.toJSON(entity));
        //移库操作
        if ("1".equals(entity.getType())) {
            FloodAssetsStock oldStock = new FloodAssetsStock();
            Queryable queryable = QueryRequest.newQueryable();
            queryable.addCondition("id", entity.getId());
            oldStock = assetsStockService.get(queryable);
            if (null != oldStock && oldStock.getStockLocation().equals(entity.getStockLocation())) {
                throw new FFException("库存点与之前相同，移动失败。");
            }

            FloodAssetsStockRecord oldRecord = new FloodAssetsStockRecord();
            BeanUtils.copyProperties(oldStock, oldRecord);
            oldRecord.setId(null);
            oldRecord.setChangeQty(oldStock.getStockQty());
            oldRecord.setChangeType(FloodStockChangeTypeEnum.MOVE_OUT.getName());
            oldRecord.setStatus(FloodStockRecordStatusEnum.TO_CHECK.getValue());       //待审核
            oldRecord.setGroupId(IdWorker.get32UUID());
            oldRecord.setApplyUserId(user.getId());
            oldRecord.setApplyUserName(user.getUsername());
            oldRecord.setApplyUserRealName(user.getRealname());
            super.insert(oldRecord);            //移库出库

            oldRecord.setId(null);
            oldRecord.setStockLocation(entity.getStockLocation());
            oldRecord.setChangeType(FloodStockChangeTypeEnum.MOVE_IN.getName());
            super.insert(oldRecord);            //移库入库
        } else {       //出库操作
            FloodAssetsStock outStock = new FloodAssetsStock();
            Queryable queryable = QueryRequest.newQueryable();
            queryable.addCondition("id", entity.getId());
            outStock = assetsStockService.get(queryable);
            if (null != outStock && entity.getStockQty().compareTo(outStock.getStockQty()) < 1) {
                FloodAssetsStockRecord outRecord = new FloodAssetsStockRecord();
                BeanUtils.copyProperties(outStock, outRecord);
                outRecord.setId(null);
                outRecord.setChangeType(FloodStockChangeTypeEnum.OUT.getName());
                outRecord.setChangeQty(entity.getStockQty());
                outRecord.setStatus(FloodStockRecordStatusEnum.TO_CHECK.getValue());
                outRecord.setApplyUserId(user.getId());
                outRecord.setApplyUserName(user.getUsername());
                outRecord.setApplyUserRealName(user.getRealname());
                super.insert(outRecord);
            } else {
                throw new FFException("库存不足。");
            }
        }
        return true;
    }

    public boolean check(FloodAssetsStockRecord stockRecord) {
        log.info("flood assets stock check>>>>>>>>> FloodAssetsStockRecord is:" + JSON.toJSON(stockRecord));
        User user = UserUtils.getUser();
        Queryable queryable = QueryRequest.newQueryable();
        queryable.addCondition("id", stockRecord.getId());
        FloodAssetsStockRecord stockRecord1 = super.get(queryable);
        log.info("stock record1 is:" + JSON.toJSON(stockRecord1));
        FloodAssetsStockRecord stockRecord2 = new FloodAssetsStockRecord();
        //审核通过
        if (FloodStockRecordStatusEnum.CHECK_SUCCESS.getValue().equals(stockRecord.getStatus())) {
            FloodAssetsStock oldAssetStock = new FloodAssetsStock();
            if (null != stockRecord1) {
                Queryable queryableStock = QueryRequest.newQueryable();
                queryableStock.addCondition("assets_code", stockRecord1.getAssetsCode());
                queryableStock.addCondition("stock_location", stockRecord1.getStockLocation());
                oldAssetStock = assetsStockService.get(queryableStock);
                //入库
                if (FloodStockChangeTypeEnum.IN.getName().equals(stockRecord1.getChangeType())) {
                    if (null != oldAssetStock) {
                        oldAssetStock.setStockQty(oldAssetStock.getStockQty().add(stockRecord1.getChangeQty()));
                        assetsStockService.updateAllColumnById(oldAssetStock);
                    } else {
                        FloodAssetsStock oldAssetStock1 = new FloodAssetsStock();
                        oldAssetStock1.setAssetsCode(stockRecord1.getAssetsCode());
                        oldAssetStock1.setAssetsName(stockRecord1.getAssetsName());
                        oldAssetStock1.setStockQty(stockRecord1.getChangeQty());
                        oldAssetStock1.setStockLocation(stockRecord1.getStockLocation());
                        oldAssetStock1.setUnit(stockRecord1.getUnit());
                        oldAssetStock1.setDelFlag("0");
                        oldAssetStock1.setCreateBy(user.getId());
                        oldAssetStock1.setUpdateBy(user.getId());
                        oldAssetStock1.setCreateDate(new Date());
                        oldAssetStock1.setUpdateDate(new Date());
                        log.info("oldAssetStock is:" + JSON.toJSON(oldAssetStock1));
                        assetsStockService.insertAllColumn(oldAssetStock1);
                    }
                } else if (FloodStockChangeTypeEnum.OUT.getName().equals(stockRecord1.getChangeType())) {
                    //出库
                    if (null == oldAssetStock || stockRecord1.getChangeQty().compareTo(oldAssetStock.getStockQty()) == 1) {
                        throw new FFException("库存不足。");
                    } else {
                        oldAssetStock.setStockQty(oldAssetStock.getStockQty().subtract(stockRecord1.getChangeQty()));
                        assetsStockService.updateAllColumnById(oldAssetStock);
                    }
                } else {

                    Queryable queryable2 = QueryRequest.newQueryable();
                    queryable2.addCondition("group_id", stockRecord1.getGroupId());
                    stockRecord2 = super.get(queryable2);

                    Queryable queryableAsset = QueryRequest.newQueryable();
                    queryableAsset.addCondition("assets_code", stockRecord2.getAssetsCode());
                    queryableAsset.addCondition("stock_location", stockRecord2.getStockLocation());
                    FloodAssetsStock stock2 = assetsStockService.get(queryableAsset);
                    //移库
                    if (FloodStockChangeTypeEnum.MOVE_OUT.getName().equals(stockRecord1.getChangeType())) {
                        if (null == oldAssetStock || stockRecord1.getChangeQty().compareTo(oldAssetStock.getStockQty()) == 1) {
                            throw new FFException("库存不足。");
                        } else {
                            oldAssetStock.setStockQty(oldAssetStock.getStockQty().subtract(stockRecord1.getChangeQty()));
                            assetsStockService.updateAllColumnById(oldAssetStock);

                            stock2.setStockQty(stock2.getStockQty().add(stockRecord2.getChangeQty()));
                            assetsStockService.updateAllColumnById(stock2);
                        }
                    } else if (FloodStockChangeTypeEnum.MOVE_IN.getName().equals(stockRecord1.getChangeType())) {
                        if (null == stock2 || stockRecord1.getChangeQty().compareTo(stock2.getStockQty()) == 1) {
                            throw new FFException("库存不足。");
                        } else {
                            stock2.setStockQty(oldAssetStock.getStockQty().subtract(stockRecord1.getChangeQty()));
                            assetsStockService.updateAllColumnById(stock2);

                            oldAssetStock.setStockQty(oldAssetStock.getStockQty().add(stockRecord2.getChangeQty()));
                            assetsStockService.updateAllColumnById(oldAssetStock);
                        }
                    }
                    stockRecord2.setCheckTime(new Date());
                    stockRecord2.setCheckUserId(user.getId());
                    stockRecord2.setCheckUserName(user.getUsername());
                    stockRecord2.setStatus(FloodStockRecordStatusEnum.CHECK_SUCCESS.getValue());
                    super.updateAllColumnById(stockRecord2);
                }
            }
            //更新操作记录状态
            stockRecord1.setStatus(FloodStockRecordStatusEnum.CHECK_SUCCESS.getValue());
        } else if (FloodStockRecordStatusEnum.CHECK_FAILED.getValue().equals(stockRecord.getStatus())) {               //审核不通过
            //更新操作记录状态
            stockRecord1.setStatus(FloodStockRecordStatusEnum.CHECK_FAILED.getValue());

            stockRecord2.setCheckTime(new Date());
            stockRecord2.setCheckUserId(user.getId());
            stockRecord2.setCheckUserName(user.getUsername());
            stockRecord2.setStatus(FloodStockRecordStatusEnum.CHECK_FAILED.getValue());
            super.updateAllColumnById(stockRecord2);
        }
        stockRecord1.setCheckTime(new Date());
        stockRecord1.setCheckUserId(user.getId());
        stockRecord1.setCheckUserName(user.getUsername());
        stockRecord1.setUpdateBy(user.getId());
        stockRecord1.setUpdateDate(new Date());
        super.updateById(stockRecord1);
        return true;
    }
}
